package net.tngou.jtdb.netty;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;

import net.tngou.db.util.ResultSet;
import net.tngou.db.util.SerializationUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

public class TngouClient {

	 
//	 static Response set =new Response();
	
	  Channel channel=null;
	  ClientHandler clh=new ClientHandler();

	  EventLoopGroup group = new NioEventLoopGroup();
	 
	 
	public TngouClient()
	 {
		 
		 Bootstrap boot = new Bootstrap();
		 
		 boot.group(group)
		 .channel(NioSocketChannel.class)
		  .option(ChannelOption.TCP_NODELAY, true)
		  .handler(new ChannelInitializer<SocketChannel>() {
			  
			  @Override
			  public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();

			  	pipeline.addLast(new ObjectEncoder());
			  	pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
			  	pipeline.addLast(clh);
			  	
			  	}

			
		  });
		  
		 try {
			 
			
				Configurations configs = new Configurations();
				File ynhouFile = new File("tngou.properties");
				PropertiesConfiguration config = configs.properties(ynhouFile);
				String HOST = config.getString("host");
				int PORT = config.getInt("port");
			 channel = boot.connect(HOST, PORT).sync().channel();
		} catch (InterruptedException | ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
	 
	 
	 
	 public ResultSet exe(String sql) throws IOException, InterruptedException {
		 ChannelFuture cf = null;
		 ResultSet res= new ResultSet();
		 res.setMsg(sql);
		 byte[] bytes = SerializationUtils.serialize(res);
		 
		 cf = channel.writeAndFlush(bytes);
		 cf.sync();
		 ResultSet response =null;
//		 Thread.sleep(20);
		 response=clh.getResponse();
		 while (response==null) {
			 Thread.sleep(1);
			 response=clh.getResponse();
			
		}
			
		clh.clearResponse();
//		 channel.closeFuture().sync();
//		if(sql.startsWith("exit"))
		
			 
		return response;
	}
	 
	 
	 public void close() {
		 group.shutdownGracefully();	
	}
	 
	 
	 // Client服务启动器  
 public static void name(String args[]) throws IOException {  	  
  
//	 EventLoopGroup group = new NioEventLoopGroup();
//	 try {
//
//		 Bootstrap b = new Bootstrap();
//		 b.group(group)
//		 .channel(NioSocketChannel.class)
//		 .option(ChannelOption.TCP_NODELAY, true)
//		 .handler(new ClientInitializer());
//		 // Make the connection attempt.
//		 Channel f = b.connect(HOST, PORT).sync().channel();
//		 // Wait until the connection is closed.
//		
//		 ChannelFuture lastWriteFuture = null;
//		 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//		 for (;;) {
//		 String line = in.readLine();
//		 if (line == null) {
//		 break;
//		 }
//		 // Sends the received line to the server.
//		 ResultSet response  = new ResultSet();
//		 
//		  response.setMsg(line);
//		 byte[] bytes = SerializationUtils.serialize(response);
//		 lastWriteFuture = f.writeAndFlush(bytes);
//	
//		 if (line.toLowerCase().startsWith("exit")) {
//		   f.closeFuture().sync();
//		 break;
//		 }
//		 }
//		
//		 // Wait until all messages are flushed before closing the channel.
//		 if (lastWriteFuture != null) {
//		 lastWriteFuture.sync();
//		 }
//		
//		
//		 
//	
//	} catch (InterruptedException  e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	
// 	} finally {
// 		group.shutdownGracefully();
//	 }
	 
 }




 
 
 
	
}
